--[[
    Author          ZhengFeng
    Time            2020.12.09
    Description     宠物拟变界面-预览
]]--

require "Common/define"
require "Logic/PetManager"
local Page_PetMatingPreview = UIBase.New(PanelResNames.Page_PetMatingPreview)
local this = Page_PetMatingPreview
local MutateType = {
    NoMutate = 0,
    OneMutant = 1,
    TwoMutate = 2,
    ThreeMutate = 3,
}
local GeneType = {
    Genetic = 0, --遗传
    Mutant = 1, --突变
    Null = 2, --空
}

local partListIndex = 0
local partListSelected = 1

local maxCount = 10000
local minProbability = 1 / maxCount
local PaternalGeneMaxHierarchy = 100
local geneBank = {}

function this:Init()
    UIBase.Init(this)
end

function this:OnCreate()
    self.Btn_BGClose = self:GetChild("Btn_BGClose")
    self:RegisterOnClick(self.Btn_BGClose, self.onClickClose)
    self.Btn_Back = self:GetChild("Btn_Back")
    self:RegisterOnClick(self.Btn_Back, self.onClickClose)
    --self.List_Part = self:GetChild("List_Part")
    --self.List_Part.itemRenderer = this.rendererPartListItem
    self:GetChild("Bg"):GetChild("title").text = getLanguage("PetMating_Title_Preview")
    self:GetChild("Txt_Genetic").text = getLanguage("PetMating_Heredity")
    self:GetChild("Txt_Mutate").text = getLanguage("PetMating_Mutation")

    self.MutateController = self:GetController("MutateType")
    self.Combo_Genetic1 = self:GetChild("Combo_Genetic1")
    self.Combo_Genetic1:GetChild("title").text = getLanguage("PetMating_HeredityRate")
    self.Combo_Genetic1:GetController("GeneType"):SetSelectedIndex(GeneType.Genetic)
    self.Combo_Genetic2 = self:GetChild("Combo_Genetic2")
    self.Combo_Genetic2:GetController("GeneType"):SetSelectedIndex(GeneType.Genetic)
    self.Combo_Genetic2:GetChild("title").text = getLanguage("PetMating_HeredityRate")

    self.Combo_Mutate1 = self:GetChild("Combo_Mutate1")
    self.Combo_Mutate1:GetController("GeneType"):SetSelectedIndex(GeneType.Mutant)
    self.Combo_Mutate1:GetChild("title").text = getLanguage("PetMating_MutationRate")
    self.Combo_Mutate2 = self:GetChild("Combo_Mutate2")
    self.Combo_Mutate2:GetController("GeneType"):SetSelectedIndex(GeneType.Mutant)
    self.Combo_Mutate2:GetChild("title").text = getLanguage("PetMating_MutationRate")
    self.Combo_Mutate3 = self:GetChild("Combo_Mutate3")
    self.Combo_Mutate3:GetController("GeneType"):SetSelectedIndex(GeneType.Mutant)
    self.Combo_Mutate3:GetChild("title").text = getLanguage("PetMating_MutationRate")
    self.Btn_Evolution = self:GetChild("Btn_Evolution");
    self:RegisterOnClick(self.Btn_Evolution, self.onClickEvolution)
    self.EvolutionInfo = self:GetChild("EvolutionInfo");
    self.MutationInfo = self:GetChild("MutationInfo");
    self.MutationController = self:GetController("nibian");

end

function this:refreshEvolution(type)
    for i, v in pairs(self.partBtn) do
        if i == type then
            v.selected = true;
        else
            v.selected = false;
        end
    end

    local TemplatePet = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
    if TemplatePet == nil then
        TemplatePet = PetManager.OtherPetInfo;
        self.MutationController.selectedIndex = 1;
    else
        self.MutationController.selectedIndex = 0;
    end
    local MutatePet = PetManager.GetPetInfoByPetId(PetManager.TemplatePetId)
    if MutatePet == nil then
        MutatePet = PetManager.OtherPetInfo;
        self.MutationController.selectedIndex = 1;
    else
        self.MutationController.selectedIndex = 0;
    end

    for i, v in pairs(TemplatePet.genes) do
        local TemplateCfg = G.dataTable["t_elvesgene"][tostring(v)];
        local MutateCfg = G.dataTable["t_elvesgene"][tostring(MutatePet.genes[i])];
        if type == TemplateCfg.f_ChromosomeId then
            local EvolutionInfoTemplate = self.EvolutionInfo:GetChild("Btn_BeforePart");--本体-本体部件图标
            local EvolutionInfoMutate = self.EvolutionInfo:GetChild("Btn_AfterPart");--本体-拟变体部件图标
            local MutationInfoTemplate = self.MutationInfo:GetChild("Btn_BeforePart");--突变-本体部件图标
            local MutationInfoMutate = self.MutationInfo:GetChild("Btn_AfterPart");--突变-突变部件图标
            local MutationCfg = G.dataTable["t_elvesmutate"][tostring(TemplateCfg.f_ChromosomeId)];

            local p1 = 0;--突变总概率1
            if TemplateCfg.f_MutationLevel == MutationCfg.f_PaternalGene1 and MutateCfg.f_MutationLevel == MutationCfg.f_PaternalGene2 then
                p1 = MutationCfg["f_MutateRate"];
            end

            local p2 = 0;--突变总概率2
            local w1 = TemplateCfg.f_SelectWeight;
            local w2 = MutateCfg.f_SelectWeight;

            local MutationInfoNum = math.max(0.01, ((p1 + p2) * 0.0001 - p1 * 0.0001 * p2 * 0.0001) * 10000 / 10000) * 100 .. "%";
            local EvolutionInfoNum = math.max(0.01, ((1 - p1 * 0.0001) * (1 - p2 * 0.0001) * w2 / (w1 + w2)) * 10000 / 10000) * 100 .. "%";
            self.EvolutionInfo:GetChild("Text_Probability").text = EvolutionInfoNum;
            self.MutationInfo:GetChild("Text_Probability").text = MutationInfoNum;

            local ctrlItem = CtrlManager.GetCtrl(PanelNames.PetPartItem);
            local MutationList = decodeJsonStrToTabel(MutationCfg.f_ProgenGene);
            local MutationId = 0
            if MutationList ~= nil then
                MutationId = MutationList[math.floor(math.random(1, #MutationList))][1];
                self.MutationInfo.visible = true;
                ctrlItem.initData(MutationInfoTemplate, TemplateCfg.f_GeneId);
                ctrlItem.initData(MutationInfoMutate, MutationId);

            else
                self.MutationInfo.visible = false;
            end
            ctrlItem.initData(EvolutionInfoTemplate, TemplateCfg.f_GeneId);
            ctrlItem.initData(EvolutionInfoMutate, MutateCfg.f_GeneId);
        end
    end

end

function this:OnEnable()
    self.partBtn = {};
    self.startClick = 13;
    for i = 1, 13 do
        local idx = i < 10 and "0" .. i or i;
        local btn = self:GetChild("Btn_MyPetBody" .. idx);
        local lockController = btn:GetController("lock");
        btn:GetChild("title").text = getLanguage("PetPart" .. i);
        if PetManager.checkTypeIsCheck(i) then
            lockController.selectedIndex = 1;
            btn.enabled = false;
        else
            lockController.selectedIndex = 0;
            btn.enabled = true;
            if self.startClick > i then
                self.startClick = i;
            end
            self:RegisterOnClick(btn, function()
                this:refreshEvolution(i)
            end);
        end
        table.insert(self.partBtn, btn);
    end
    this:showPanel()
end

function this:OnDisable()
    --self.List_Part.onClickItem:Remove(this.onPartListItemClick)
end
function this:OnDestroy()

end

function this:onClickClose()
    closeUI(PanelResNames.Page_PetMatingPreview)
end

function this:onClickEvolution()
    if PetManager.TemplatePetId ~= 0 and PetManager.MutatePetId ~= 0 then
        local sendLockParts = {};
        for i, v in pairs(PetManager.lockParts) do
            table.insert(sendLockParts, v.type);
        end
        PetHandler.ReqSelfMating(PetManager.TemplatePetId, PetManager.MutatePetId, sendLockParts)
        self.onClickClose();
    end
end

function this:showPanel()
    local _petInfo
    local _fatherGenes = {}
    if table.getn(PetManager.OtherPetInfo) > 0 then
        _fatherGenes = PetManager.OtherPetInfo.genes
    elseif PetManager.TemplatePetId ~= 0 then
        _petInfo = PetManager.GetPetInfoByPetId(PetManager.TemplatePetId)
        _fatherGenes = _petInfo.genes
    end

    local _motherGenes = {}
    if PetManager.MutatePetId ~= 0 then
        _petInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
        _motherGenes = _petInfo.genes
    end

    local _geneConfig = G.dataTable["t_elvesgene"]
    geneBank = {}
    for key, _fatherGeneId in pairs(_fatherGenes) do
        local _fatherGeneInfo = _geneConfig[tostring(_fatherGeneId)]
        local _fatherGeneName = getLanguage(_fatherGeneInfo.f_GeneName)
        local _fatherGeneIcon = PetManager.GetPetIconByGeneInfo(_fatherGeneInfo)
        local _fatherGeneRate = _fatherGeneInfo.f_SelectWeight
        local _fatherMutationLevel = _fatherGeneInfo.f_MutationLevel
        local _fatherInfo = { GeneId = _fatherGeneId, GeneName = _fatherGeneName, GeneIcon = _fatherGeneIcon,
                              GeneRate = _fatherGeneRate, MutationLevel = _fatherMutationLevel }

        local _motherGeneId = _motherGenes[key]
        local _motherGeneInfo = _geneConfig[tostring(_motherGeneId)]
        local _motherGeneName = getLanguage(_motherGeneInfo.f_GeneName)
        local _motherGeneIcon = PetManager.GetPetIconByGeneInfo(_motherGeneInfo)
        local _motherGeneRate = _motherGeneInfo.f_SelectWeight
        local _motherMutationLevel = _motherGeneInfo.f_MutationLevel
        local _motherInfo = { GeneId = _motherGeneId, GeneName = _motherGeneName, GeneIcon = _motherGeneIcon,
                              GeneRate = _motherGeneRate, MutationLevel = _motherMutationLevel }

        local _bankInfo = { FatherGeneticInfo = _fatherInfo, MotherGeneticInfo = _motherInfo, IdMutateInfo = {}, LvMutateInfo = {} }
        table.insert(geneBank, _bankInfo)
    end

    local _mutateConfig = G.dataTable["t_elvesmutate"]
    for _, mutateInfo in pairs(_mutateConfig) do
        local _partIndex = mutateInfo.f_ChromosomeId
        local _parentGene1 = mutateInfo.f_PaternalGene1
        local _parentGene2 = mutateInfo.f_PaternalGene2
        local _fatherGeneticInfo = geneBank[_partIndex].FatherGeneticInfo
        local _motherGeneticInfo = geneBank[_partIndex].MotherGeneticInfo

        --两个都是基因id
        if _parentGene1 > PaternalGeneMaxHierarchy and _parentGene2 > PaternalGeneMaxHierarchy then
            if (_parentGene1 == _fatherGeneticInfo.GeneId and _parentGene2 == _motherGeneticInfo.GeneId)
                    or (_parentGene2 == _fatherGeneticInfo.GeneId and _parentGene1 == _motherGeneticInfo.GeneId) then
                local _geneId = mutateInfo.f_ProgenGene[1][1]
                local _geneInfo = _geneConfig[tostring(_geneId)]
                local _geneName = getLanguage(_geneInfo.f_GeneName)
                local _geneIcon = PetManager.GetPetIconByGeneInfo(_geneInfo)
                local _geneRate = mutateInfo.f_MutateRate
                local _mutationLevel = _geneInfo.f_MutationLevel
                local _idMutateInfo = { GeneId = _geneId, GeneName = _geneName, GeneIcon = _geneIcon, GeneRate = _geneRate, MutationLevel = _mutationLevel }
                geneBank[_partIndex].IdMutateInfo = _idMutateInfo
            end
            --两个都是突变层级lv (不要问程序为什么这段代码写的这么挫)
        elseif _parentGene1 <= PaternalGeneMaxHierarchy and _parentGene2 <= PaternalGeneMaxHierarchy then
            if (_parentGene1 == _fatherGeneticInfo.MutationLevel and _parentGene2 == _motherGeneticInfo.MutationLevel)
                    or (_parentGene2 == _fatherGeneticInfo.MutationLevel and _parentGene1 == _motherGeneticInfo.MutationLevel) then
                local _genes = mutateInfo.f_ProgenGene
                if string.IsNilOrEmpty(_genes) then
                    geneBank[_partIndex].LvMutateInfo1 = {}
                    geneBank[_partIndex].LvMutateInfo2 = {}
                else
                    local _geneRate = mutateInfo.f_MutateRate
                    local _gene1Id = _genes[1][1]
                    local _gene1Weight = _genes[1][2]
                    local _gene1Info = _geneConfig[tostring(_gene1Id)]
                    local _gene1Name = getLanguage(_gene1Info.f_GeneName)
                    local _gene1Icon = PetManager.GetPetIconByGeneInfo(_gene1Info)
                    local _gene1MutationLevel = _gene1Info.f_MutationLevel
                    local _lvMutateInfo1 = { GeneId = _gene1Id, GeneName = _gene1Name, GeneIcon = _gene1Icon, GeneRate = _geneRate,
                                             MutationLevel = _gene1MutationLevel, Weight = _gene1Weight }
                    geneBank[_partIndex].LvMutateInfo1 = _lvMutateInfo1

                    if _genes[2] then
                        local _gene2Id = _genes[2][1]
                        local _gene2Weight = _genes[2][2]
                        local _gene2Info = _geneConfig[tostring(_gene2Id)]
                        local _gene2Name = getLanguage(_gene2Info.f_GeneName)
                        local _gene2Icon = PetManager.GetPetIconByGeneInfo(_gene2Info)
                        local _gene2MutationLevel = _gene2Info.f_MutationLevel
                        local _lvMutateInfo2 = { GeneId = _gene2Id, GeneName = _gene2Name, GeneIcon = _gene2Icon, GeneRate = _geneRate,
                                                 MutationLevel = _gene2MutationLevel, Weight = _gene2Weight }
                        geneBank[_partIndex].LvMutateInfo2 = _lvMutateInfo2
                    end
                end

            end
        end
    end

    partListIndex = 0
    partListSelected = 1
    --self.List_Part.numItems = #geneBank
    --self.List_Part.onClickItem:Add(this.onPartListItemClick)
    this:refreshPreviewInfo()
    this:refreshEvolution(self.startClick);
end

function this:rendererPartListItem(obj)
    partListIndex = partListIndex + 1
    local _partName = getLanguage("PetPart" .. tostring(partListIndex))
    obj:GetChild("title").text = _partName
    obj.selected = partListIndex == partListSelected
    obj:GetController("level"):SetSelectedIndex(0)
end
function this.onPartListItemClick(context)
    local _obj = context.data
    --partListSelected = this.List_Part:GetChildIndex(_obj) + 1
    this:refreshPreviewInfo()
end

function this:refreshPreviewInfo()
    local _fatherGeneticInfo = geneBank[partListSelected].FatherGeneticInfo
    local _motherGeneticInfo = geneBank[partListSelected].MotherGeneticInfo
    local _idMutateInfo = geneBank[partListSelected].IdMutateInfo
    local _lvMutateInfo1 = geneBank[partListSelected].LvMutateInfo1
    local _lvMutateInfo2 = geneBank[partListSelected].LvMutateInfo2
    local p1 = 0
    local p2 = 0
    local w1 = _fatherGeneticInfo.GeneRate
    local w2 = _motherGeneticInfo.GeneRate
    local _wCount = w1 + w2
    local _lvWeightCount = 0

    if table.getn(_idMutateInfo) > 0 then
        p1 = _idMutateInfo.GeneRate
    end
    if table.getn(_lvMutateInfo1) > 0 then
        _lvWeightCount = _lvWeightCount + _lvMutateInfo1.Weight
        p2 = _lvMutateInfo1.GeneRate
    end
    if table.getn(_lvMutateInfo2) > 0 then
        _lvWeightCount = _lvWeightCount + _lvMutateInfo2.Weight
    end

    local _idMutateRate = p1 / maxCount
    local _lvMutateRateCount = (1 - _idMutateRate) * p2 / maxCount
    local _fatherGeneRate = (1 - _idMutateRate - _lvMutateRateCount) * w1 / _wCount
    local _motherGeneRate = (1 - _idMutateRate - _lvMutateRateCount) * w2 / _wCount

    local _lvMutateRate1 = 0
    if table.getn(_lvMutateInfo1) > 0 then
        _lvMutateRate1 = _lvMutateRateCount * _lvMutateInfo1.Weight / _lvWeightCount
    end
    local _lvMutateRate2 = 0
    if table.getn(_lvMutateInfo2) > 0 then
        _lvMutateRate2 = _lvMutateRateCount * _lvMutateInfo2.Weight / _lvWeightCount
    end

    this:setComboInfo(self.Combo_Genetic1, _fatherGeneticInfo, _fatherGeneRate)
    this:setComboInfo(self.Combo_Genetic2, _motherGeneticInfo, _motherGeneRate)

    local _type = MutateType.NoMutate
    if table.getn(_idMutateInfo) > 0 then
        this:setComboInfo(self.Combo_Mutate1, _idMutateInfo, _idMutateRate)
        if table.getn(_lvMutateInfo1) > 0 then
            this:setComboInfo(self.Combo_Mutate2, _lvMutateInfo1, _lvMutateRate1)
            if table.getn(_lvMutateInfo2) > 0 then
                _type = MutateType.ThreeMutate
                this:setComboInfo(self.Combo_Mutate3, _lvMutateInfo2, _lvMutateRate2)
            else
                _type = MutateType.TwoMutate
            end
        else
            _type = MutateType.OneMutant
        end
    elseif table.getn(_lvMutateInfo1) > 0 then
        this:setComboInfo(self.Combo_Mutate1, _lvMutateInfo1, _lvMutateRate1)
        if table.getn(_lvMutateInfo2) > 0 then
            _type = MutateType.TwoMutate
            this:setComboInfo(self.Combo_Mutate2, _lvMutateInfo2, _lvMutateRate2)
        else
            _type = MutateType.OneMutant
        end
    end
    self.MutateController:SetSelectedIndex(_type)
end
function this:setComboInfo(comboGO, mutateInfo, mutateRate)
    comboGO:GetChild("Img_GeneIcon").url = mutateInfo.GeneIcon
    comboGO:GetChild("Txt_GeneName").text = mutateInfo.GeneName
    comboGO:GetChild("Txt_GeneRate").text = Util.NumberPercent(mutateRate)
    comboGO:GetController("level"):SetSelectedIndex(mutateInfo.MutationLevel - 1)
end

return this